package com.ktg.mes.dv.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.BaseEntity;
import com.ktg.mes.dv.domain.DvTemperatureData;
import com.ktg.mes.dv.domain.FindWattHourOpenTimeParam;
import com.ktg.mes.dv.service.IDvTemperatureDataService;
import com.ktg.mes.util.LGQueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.dv.domain.DvWattHourMeterData;
import com.ktg.mes.dv.service.IDvWattHourMeterDataService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 电表数据Controller
 *
 * @author byteco
 * @date 2022-11-30
 */
@RestController
@RequestMapping("/dv/dvWattHourMeterData")
public class DvWattHourMeterDataController extends BaseController
{
    @Autowired
    private IDvWattHourMeterDataService dvWattHourMeterDataService;

    @Autowired
    private IDvTemperatureDataService dvTemperatureDataService;

    /**
     * 查询电表数据列表
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:list')")
    @GetMapping("/list")
    public Result<IPage<DvWattHourMeterData>> list(DvWattHourMeterData dvWattHourMeterData,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询电表数据列表",req,null);
        try {
            Page<DvWattHourMeterData> page = new Page<DvWattHourMeterData>(pageNo, pageSize);
            LGQueryWrapper<DvWattHourMeterData> lqw = new  LGQueryWrapper(dvWattHourMeterData,req.getParameterMap());
            lqw.orderByDesc("create_time");
            IPage<DvWattHourMeterData> pageList = dvWattHourMeterDataService.page(page,lqw);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }



    /**
     * 查询电表按分钟区分的数据数据，按1200 之内条数据统计展示
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:list')")
    @GetMapping("/chartMinute")
    public Result<IPage<DvWattHourMeterData>> chartMinute(DvWattHourMeterData dvWattHourMeterData,
                                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                   HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询电表数据列表",req,null);
        try {
            //获取总数量
            LGQueryWrapper<DvWattHourMeterData> lqw = new  LGQueryWrapper(dvWattHourMeterData,req.getParameterMap());
            lqw.select("COUNT(0) as count,MIN(DISTINCT(create_time)) as startTime,MAX(create_time) as endTime");
            Map findMap = dvWattHourMeterDataService.getMap(lqw);

            if (findMap == null || findMap.get("count") == null || Long.valueOf(findMap.get("count").toString()) == 0){
                return apiLog.ok(null);
            };
            Long count = Long.valueOf(findMap.get("count").toString());
            //默认统计类型，如果数据太多修改统计时间
            String[] dateStr = {"DATE_FORMAT(create_time,'%Y-%m-%d %H:%i分')"
                    ,"DATE_FORMAT(create_time,'%Y-%m-%d %H时')"
                    ,"DATE_FORMAT(create_time,'%Y-%m-%d')"
                    ,"DATE_FORMAT(create_time,'%Y-%m')"
            };
            int[] spaceList = {60*60*30
                    ,60*60*24*30
                    ,60*60*24*30*30
                    ,60*60*24*30*12*30
            };

            String selectDateStr = "DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s')";
            if (count > 60){
                for(int i = 0; i < dateStr.length; i++) {
                    if (count > spaceList[i]){
                        continue;
                    }else {
                        selectDateStr = dateStr[i];
                        break;
                    }
                };
            }
            /* 使用PGSql的窗口函数实现分组的同时带上其他字段，参考： https://www.skypyb.com/2021/08/jishu/1871/
            SELECT
            distinct on (aday)
            aday,
            MAX ( ZXYGZDL ) OVER (PARTITION by aday) as count,
            device_name AS NAME
            FROM
                (
                SELECT
                    DATE_FORMAT ( create_time, '%Y-%m-%d %H:%i分' ) AS aday,
                    ZXYGZDL,
                    device_name
                FROM
                    dv_watt_hour_meter_data
                WHERE
                    ( device_name = '研磨机01' AND create_time BETWEEN '2022-12-01T00:00:00.000+0800' AND '2022-12-31T00:00:00.000+0800' AND ZXYGZDL >= 0 AND device_name IS NOT NULL AND device_name NOT IN ( '' ) )
                ) TEMP
            ORDER BY
                aday ASC;
            * */
            //获取统计数据
            QueryWrapper<DvWattHourMeterData> wattHourMeterDataQueryWrapper = new  LGQueryWrapper(dvWattHourMeterData,req.getParameterMap());
            /*
            wattHourMeterDataQueryWrapper.ge("'ZXYGZDL'","0");
            wattHourMeterDataQueryWrapper.orderByAsc("create_time");
            wattHourMeterDataQueryWrapper.isNotNull("device_name");
            wattHourMeterDataQueryWrapper.notIn("device_name","");
            wattHourMeterDataQueryWrapper.select(selectDateStr+" as aday,MAX('ZXYGZDL') as count,device_name as name");
            wattHourMeterDataQueryWrapper.groupBy(selectDateStr);
            */
//            wattHourMeterDataQueryWrapper.nested()
//            QueryWrapper<DvWattHourMeterData> outerWrapper = new  QueryWrapper();
//            outerWrapper.select("distinct on (aday) aday","MAX ( ZXYGZDL ) OVER (PARTITION by aday) as count","device_name AS NAME");
            wattHourMeterDataQueryWrapper.select(selectDateStr+" as aday,ZXYGZDL,device_name");
            System.out.println("查询条件：：：：：======" + wattHourMeterDataQueryWrapper.getCustomSqlSegment() + " ==== ");
            String selectColumn = "distinct on (aday)" +
                    "            aday," +
                    "            MAX ( ZXYGZDL ) OVER (PARTITION by aday) as count," +
                    "            device_name AS NAME ";
            List mapList = dvWattHourMeterDataService.chartMinute(wattHourMeterDataQueryWrapper,selectColumn);



//            QueryWrapper<DvWattHourMeterData> outerWrapper = new QueryWrapper();
//            outerWrapper.nested(wattHourMeterDataQueryWrapper);
//            List mapList = dvWattHourMeterDataService.listMaps(wattHourMeterDataQueryWrapper);

//            List mapList = dvWattHourMeterDataService.listMaps(wattHourMeterDataQueryWrapper);
            return apiLog.ok(mapList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 查询开机时长统计,同时统计温度
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:list')")
    @GetMapping("/findWattHourOpenTime")
    public Result findWattHourOpenTime(FindWattHourOpenTimeParam hourOpenTimeParam,
                                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                          HttpServletRequest req){
        APIResult apiLog = new APIResult("查询开机时长统计,同时统计温度",req,null);
        try {
            List list = dvWattHourMeterDataService.findWattHourOpenTime(hourOpenTimeParam);
            return apiLog.ok(list);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }



    /**
     * 查询电表按分钟区分的数据数据，按1200 之内条数据统计展示
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:list')")
    @GetMapping("/chartPower")
    public Result<IPage<DvWattHourMeterData>> chartPower(DvWattHourMeterData dvWattHourMeterData,
                                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                          HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询电表数据列表",req,null);
        try {
            //获取总数量
            LGQueryWrapper<DvWattHourMeterData> lqw = new  LGQueryWrapper(dvWattHourMeterData,req.getParameterMap());
            lqw.select("COUNT(0) as count,MIN(DISTINCT(create_time)) as startTime,MAX(create_time) as endTime");
            Map findMap = dvWattHourMeterDataService.getMap(lqw);
            if (findMap == null || findMap.get("count") == null || Long.valueOf(findMap.get("count").toString()) == 0){
                return apiLog.ok(null);
            };
            Long count = Long.valueOf(findMap.get("count").toString());
            //默认统计类型，如果数据太多修改统计时间
            String[] dateStr = {"DATE_FORMAT(create_time,'%Y-%m-%d %H:%i分')"
                    ,"DATE_FORMAT(create_time,'%Y-%m-%d %H时')"
                    ,"DATE_FORMAT(create_time,'%Y-%m-%d')"
                    ,"DATE_FORMAT(create_time,'%Y-%m')"
            };
            int[] spaceList = {60*60*30
                    ,60*60*24*30
                    ,60*60*24*30*30
                    ,60*60*24*30*12*30
            };

            String selectDateStr = "DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s')";
            if (count > 60){
                for(int i = 0; i < dateStr.length; i++) {
                    if (count > spaceList[i]){
                        continue;
                    }else {
                        selectDateStr = dateStr[i];
                        break;
                    }
                };
            }

            //获取统计数据
            QueryWrapper<DvWattHourMeterData> wattHourMeterDataQueryWrapper = new  LGQueryWrapper(dvWattHourMeterData,req.getParameterMap());
            wattHourMeterDataQueryWrapper.select(selectDateStr+" as aday,zszgl,device_name");

            wattHourMeterDataQueryWrapper.ge("zszgl",0);
//            wattHourMeterDataQueryWrapper.orderByAsc("create_time");
            wattHourMeterDataQueryWrapper.isNotNull("device_name");
            wattHourMeterDataQueryWrapper.notIn("device_name","");
            wattHourMeterDataQueryWrapper.select(selectDateStr+" as aday,zszgl,device_name");
//            wattHourMeterDataQueryWrapper.select(selectDateStr+" as aday,MAX('zszgl') as count,CONCAT(device_name,'-电表') as name");
//            wattHourMeterDataQueryWrapper.groupBy(selectDateStr);

            String selectColumn = "distinct on (aday) aday," +
                    "            MAX ( zszgl ) OVER (PARTITION by aday) as count," +
                    "            CONCAT(device_name,'-电表') AS NAME ";
            List mapList = dvWattHourMeterDataService.chartMinute(wattHourMeterDataQueryWrapper,selectColumn);


            //获取统计数据
            DvTemperatureData temperatureData = new DvTemperatureData();
            temperatureData.setBatchNo(dvWattHourMeterData.getBatchNo());
            temperatureData.setDeviceName(dvWattHourMeterData.getDeviceName());
            temperatureData.setProcessName(dvWattHourMeterData.getProcessName());
            temperatureData.setCreateTime(dvWattHourMeterData.getCreateTime());
            temperatureData.setDeviceCode(dvWattHourMeterData.getDeviceCode());

            //获取统计数据
            QueryWrapper<DvTemperatureData> tQueryWrapper = new LGQueryWrapper(temperatureData,req.getParameterMap());
            tQueryWrapper.ge("temp1",1);
            tQueryWrapper.isNotNull("device_name");
            tQueryWrapper.notIn("device_name","");
            tQueryWrapper.select(selectDateStr+" as aday,temp1,device_name");
            selectColumn = " distinct on (aday) aday, MAX ( temp1 ) OVER (PARTITION BY aday) as count ,CONCAT ( device_name, '-温度' ) AS NAME ";
            List mapList1 = dvTemperatureDataService.chartMinute(tQueryWrapper,selectColumn);

            Map<String,List> listMap = new HashMap<>();
            listMap.put("left",mapList);
            listMap.put("right",mapList1);

            return apiLog.ok(listMap);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 导出电表数据列表
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:export')")
    @Log(title = "电表数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvWattHourMeterData dvWattHourMeterData,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出电表数据列表",req,dvWattHourMeterData);
        try {
            List<DvWattHourMeterData> list = dvWattHourMeterDataService.queryList(dvWattHourMeterData);
            ExcelUtil<DvWattHourMeterData> util = new ExcelUtil<DvWattHourMeterData>(DvWattHourMeterData.class);
            util.exportExcel(response, list, "电表数据数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取电表数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:query')")
    @GetMapping(value = "/{recordId}")
    public Result<DvWattHourMeterData> getInfo(@PathVariable("recordId") Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取电表数据详细信息",req,null);
        try {
            return apiLog.ok(dvWattHourMeterDataService.getInfo(recordId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增电表数据
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:add')")
    @Log(title = "电表数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody DvWattHourMeterData dvWattHourMeterData,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增电表数据",req,dvWattHourMeterData);
        try {
            dvWattHourMeterDataService.insert(dvWattHourMeterData);
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改电表数据
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:edit')")
    @Log(title = "电表数据", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody DvWattHourMeterData dvWattHourMeterData,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改电表数据",req,dvWattHourMeterData);
        try {
            dvWattHourMeterDataService.update(dvWattHourMeterData);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除电表数据
     */
    @PreAuthorize("@ss.hasPermi('dv:dvWattHourMeterData:remove')")
    @Log(title = "电表数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public Result<String> remove(@PathVariable Long[] recordIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除电表数据",req,null);
        try {
            dvWattHourMeterDataService.delete(recordIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
